<?php

namespace app\controller\admin;

use app\core\ApiController;
use app\service\BlessingOrderService;
use app\service\ProductOrderService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class ProductOrder extends ApiController
{

    public function list()
    {
        $page = input('post.page', 1);
        $limit = input('post.limit', 10);
        $searchQuery = input('post.', []);
        $list = ProductOrderService::invoke()->list($page, $limit, $searchQuery);
        $this->response->success($list);
    }

    /**
     *订单详情接口
     */
    public function info()
    {
        $order_id = input('get.order_id');
        $data = ProductOrderService::invoke()->info($order_id);
        $this->response->success($data);
    }

    public function checkReturn()
    {
        $data = input('post.', []);
        $order_id = $data['order_id'];
        $data = ProductOrderService::invoke()->checkReturn($data, $order_id);
        $this->response->success($data);
    }

    public function export()
    {
        $searchQuery = input('post.', null);
        //1.从数据库中取出数据
        $list = ProductOrderService::invoke()->getExportList($searchQuery);
        $list = array_values($list);
        foreach ($list[0] as $value) {
            $data[] =
                [
                    'order_no' => $value['order_no'],
                    'name' => $value['name'],
                    'mobile' => $value['mobile'],
                    'address' => $value['address'],
                    'product_name' => $value['product_name'],
                    'price' => $value['price'],
                    'status_name' => $value['status_name'],
                    'create_time' => $value['create_time'],
                    'pay_time' => $value['pay_time'],
                    'remark' => $value['remark'],
                ];
        }

        $xlsName = "纳福商品订单" . date("YmdHis", time());//文件名称
        $head = ['订单编号', '收货人', '联系电话', '地址', '商品名称', '金额', '订单状态', '创建时间', '支付时间', '备注'];// 表头信息
        //表字段和表头信息一一对应
        $keys = ['order_no', 'name', 'mobile', 'address', 'product_name', 'price', 'status_name', 'create_time', 'pay_time', 'remark'];
        $this->downloadExcel($xlsName, $data ?? [], $head, $keys);
    }

    public function downloadExcel($name, $data = [], $head = [], $keys = [])
    {

        $count = count($head);  //计算表头数量
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        for ($i = 65; $i < $count + 65; $i++) {     //数字转字母从65开始，循环设置表头：
            $sheet->setCellValue(strtoupper(chr($i)) . '1', $head[$i - 65]);
        }
        //循环设置单元格：
        foreach ($data as $key => $item) {
            //$key+2,因为第一行是表头，所以写到表格时   从第二行开始写
            for ($i = 65; $i < $count + 65; $i++) {
                //数字转字母从65开始：
                $sheet->setCellValue(strtoupper(chr($i)) . ($key + 2), $item[$keys[$i - 65]]);
                //固定列宽
                $spreadsheet->getActiveSheet()->getColumnDimension(strtoupper(chr($i)))->setWidth(20);
            }
        }
        $names = $name;
        //utf-8转unicode格式
        $name = iconv('UTF-8', 'UCS-2BE', $name);
        $len = strlen($name);
        $str = '';
        for ($i = 0; $i < $len - 1; $i = $i + 2) {
            $c = $name[$i];
            $c2 = $name[$i + 1];
            if (ord($c) > 0) {
                $str .= '\u' . base_convert(ord($c), 10, 16) . str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
            } else {
                $str .= '\u' . str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);
            }
        }
        ob_end_clean();
        header("Content-Type:application/vnd.ms-excel");
        header("Cache-Control:max-age=0");
        header('Data-Type: binary');
        header('Data-Filename: ' . $str);
        header('Content-Disposition: attachment;filename="' . $names . '.xlsx"');
        header('Cache-Control: max-age=0');
        header('Access-Control-Expose-Headers:Data-Type,Data-Filename');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');

    }

}